<template>
	<div class="task-list-container">
		<!-- 任务表格 -->
		<el-table :data="taskList" border style="width: 100%" v-loading="loading" stripe>
			<el-table-column prop="name" label="任务名称" min-width="190" fixed="left">
				<template #default="scope">
					<div class="task-name">
						<el-text size="small" style="font-weight: 500;">{{ scope.row.name }}</el-text>
						<el-text size="small" type="info" style="display: block; margin-top: 2px;">
							{{ scope.row.description || '暂无描述' }}
						</el-text>
					</div>
				</template>
			</el-table-column>

			<el-table-column prop="type" label="类型" minwidth="80" align="center">
				<template #default="scope">
					<el-tag :type="getTypeTagType(scope.row.type)" size="small">
						{{ getTypeDisplayName(scope.row.type) }}
					</el-tag>
				</template>
			</el-table-column>

			<el-table-column prop="schedule_info" label="调度信息" min-width="120" align="center">
				<template #default="scope">
					<el-text size="small">{{ scope.row.schedule_info }}</el-text>
				</template>
			</el-table-column>

			<el-table-column label="执行统计" min-width="120" align="center">
				<template #default="scope">
					<div class="stats-info">
						<el-text size="small" style="display: block; color: var(--el-color-danger);">
							失败: {{ scope.row.failed_executions || 0 }}
						</el-text>
					</div>
				</template>
			</el-table-column>

			<el-table-column prop="enabled" label="启用状态" min-width="100" align="center">
				<template #default="scope">
					<el-tag :type="scope.row.enabled ? 'success' : 'info'" size="small">
						{{ scope.row.enabled ? '启用' : '禁用' }}
					</el-tag>
				</template>
			</el-table-column>

			<el-table-column label="执行时间" min-width="220" align="center">
				<template #default="scope">
					<div class="execution-time">
						<div class="time-item">
							<el-text size="small" type="info">
								最后执行: {{ formatTime(scope.row.last_run) }}
							</el-text>
						</div>
						<!-- <div class="time-item">
							<el-text size="small" type="warning">
								下次执行: {{ formatTime(scope.row.next_run) }}
							</el-text>
						</div> -->
					</div>
				</template>
			</el-table-column>

			<el-table-column label="操作" min-width="160" align="center" fixed="right">
				<template #default="scope">
					<el-button size="small" link type="primary" @click="handleManualExecute(scope.row)"
						:disabled="!scope.row.enabled">执行
					</el-button>
					<el-divider direction="vertical" style="margin: 0;"/>
					<el-button link type="primary" size="small" @click="handleShowLogs(scope.row.id)"> 日志
					</el-button>
					<el-divider direction="vertical" style="margin: 0;"/>

					<el-button link type="primary" size="small" @click="handleEdit(scope.row)"> 编辑
					</el-button>

				</template>
			</el-table-column>
		</el-table>

		<!-- 分页 -->
		<div class="pagination-container" style="margin-top: 16px; text-align: right;">
			<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
				:page-sizes="[10, 20, 50, 100]" :total="totalTasks" layout="total, sizes, prev, pager, next, jumper"
				@size-change="handleSizeChange" @current-change="handleCurrentChange" />
		</div>

		<!-- 空状态 -->
		<el-empty v-if="!loading && taskList.length === 0" description="暂无任务数据" />
	</div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import {
	Document,
	Edit,
	VideoPlay
} from '@element-plus/icons-vue'


export default {
	name: 'TaskList',
	components: {
		Document,
		Edit,
		VideoPlay
	},
	data() {
		return {
			taskList: [],
			loading: false,
			currentPage: 1,
			pageSize: 20,
			totalTasks: 0
		}
	},
	created() {
		this.loadData()
	},
	methods: {
		// 加载任务列表数据
		async loadData() {
			this.loading = true
			try {
				const { getTaskList } = await import('../api')
				const params = {
					page: this.currentPage,
					limit: this.pageSize
				}
				const response = await getTaskList(params)

				if (response.code === 200) {
					this.taskList = response.data.list || []
					this.totalTasks = response.data.total || 0
					this.processTaskList()
				} else {
					throw new Error(response.message || '获取任务列表失败')
				}
			} catch (error) {
				ElMessage.error('获取任务列表失败: ' + error.message)
				this.taskList = []
				this.totalTasks = 0
			} finally {
				this.loading = false
			}
		},

		// 处理任务列表数据，格式化显示字段
		processTaskList() {
			this.taskList = this.taskList.map(task => {
				// 处理调度信息显示
				let scheduleInfo = ''
				if (task.schedule_config) {
					try {
						const config = typeof task.schedule_config === 'string'
							? JSON.parse(task.schedule_config)
							: task.schedule_config

						if (task.type === 'interval') {
							scheduleInfo = `每${config.interval}秒执行`
						} else if (task.type === 'daily') {
							scheduleInfo = `每日${config.time}执行`
						} else if (task.type === 'weekly') {
							scheduleInfo = `每周${config.day_of_week} ${config.time}执行`
						} else if (task.type === 'monthly') {
							scheduleInfo = `每月${config.day_of_month}号 ${config.time}执行`
						} else if (task.type === 'cron') {
							scheduleInfo = config.cron
						}
					} catch (e) {
						scheduleInfo = '配置错误'
					}
				}

				return {
					...task,
					schedule_info: scheduleInfo,
					description: task.desc || '暂无描述',
					status: task.run_status === 'running',
					enabled: Boolean(task.enabled),
					last_run: task.last_run_time,
					next_run: task.next_run_time
				}
			})
		},

		// 获取类型标签类型
		getTypeTagType(type) {
			const typeMap = {
				'interval': 'primary',
				'daily': 'success',
				'weekly': 'warning',
				'monthly': 'info',
				'cron': 'danger'
			}
			return typeMap[type] || 'info'
		},

		// 获取类型显示名称
		getTypeDisplayName(type) {
			const typeMap = {
				'interval': '间隔',
				'daily': '每日',
				'weekly': '每周',
				'monthly': '每月',
				'cron': 'Cron'
			}
			return typeMap[type] || type
		},

		// 格式化时间
		formatTime(timeStr) {
			if (!timeStr) return '-'
			try {
				const date = new Date(timeStr)
				return date.toLocaleString('zh-CN')
			} catch (e) {
				return timeStr
			}
		},

		// 显示任务日志
		handleShowLogs(taskId) {
			this.$emit('showLogs', taskId)
		},

		// 处理编辑任务
		handleEdit(task) {
			this.$emit('editTask', task)
		},

		// 手动执行任务
		async handleManualExecute(task) {
			try {
				await ElMessageBox.confirm(
					`<div style="line-height: 1.6;">
							<p><strong>确认要立即执行一次该任务吗？</strong></p>
							<p><strong>任务名称：</strong>${task.name}</p>
							<p><strong>任务描述：</strong>${task.description}</p>
						</div>`,
					'手动执行任务',
					{
						confirmButtonText: '立即执行',
						cancelButtonText: '取消',
						type: 'warning',
						dangerouslyUseHTMLString: true
					}
				)

				// 用户确认后执行任务
				await this.executeTask(task.id)

			} catch (error) {
				if (error !== 'cancel') {
					ElMessage.error('手动执行失败: ' + error.message)
				}
			}
		},

		// 执行任务
		async executeTask(taskId) {
			const loading = ElMessage({
				message: '正在执行任务...',
				type: 'info',
				duration: 0 // 不自动关闭
			})

			try {
				const { manualExecuteTask } = await import('../api')
				const response = await manualExecuteTask(taskId)

				loading.close()

				if (response.code === 200) {
					ElMessage.success('任务执行成功！')
					// 刷新任务列表
					this.loadData()
					// 触发父组件刷新日志
					this.$emit('taskExecuted', taskId)
				} else {
					throw new Error(response.message || '任务执行失败')
				}
			} catch (error) {
				loading.close()
				throw error
			}
		},

		// 分页相关
		handleSizeChange(newSize) {
			this.pageSize = newSize
			this.currentPage = 1
			this.loadData()
		},

		handleCurrentChange(newPage) {
			this.currentPage = newPage
			this.loadData()
		}
	}
}
</script>

<style scoped>
.task-list-container {
	height: 100%;
	display: flex;
	flex-direction: column;
}

.task-name {
	line-height: 1.4;
}

.stats-info {
	line-height: 1.3;
}

.execution-time {
	display: flex;
	flex-direction: column;
	gap: 2px;
}

.time-item {
	line-height: 1.3;
}

.pagination-container {
	margin-top: auto;
	padding-top: 16px;
	border-top: 1px solid var(--el-border-color-lighter);
}

/* 响应式布局 */
@media (max-width: 768px) {
	.action-buttons {
		flex-direction: column;
		gap: 2px;
	}

	.action-buttons .el-button {
		min-width: 60px;
	}
}
</style>